<template>
  <div class='progress-bar'
       ref="progressBar"
       @click="change">
    <div class="inner">
      <div class="progess"
           ref='progress'></div>
      <div class="progress-btn"
           ref='progressBtn'
           @touchstart.stop.prevent='touchstart'
           @touchmove.stop.prevent='touchmove'
           @touchend.stop.prevent='touchend'>
      </div>
    </div>
  </div>
</template>

<script>
// 按钮的大小 减去 溢出的宽 3px
import { prefixStyle } from 'common/js/dom'
const transform = prefixStyle('transform')
const progressBtnWidth = 13
export default {
  data () {
    return {
      // 拖动标识
      touchInit: false
    }
  },
  props: {
    // 歌曲进度百分比
    percent: {
      type: Number,
      default: 0
    }
  },
  created () {
    this.Width = 0
    this.touch = {}
  },
  methods: {
    // 进度点击
    change (e) {
      console.log(e.offsetX)
      this.$emit('changeCurrentTime', e.offsetX / this.Width)
    },
    // 按钮拖动事件  禁止冒泡防止点击按钮触发change事件
    touchstart (e) {
      this.touchInit = true
      console.log(e)
      // 记录初始按钮已经走的偏移
      this.touch.offsetX = this.$refs.progress.clientWidth
      this.touch.pageX = e.touches[0].pageX
    },
    touchmove (e) {
      if (!this.touchInit) return false
      const detailX = e.touches[0].pageX - this.touch.pageX
      // 边界处理
      const offset = Math.min(Math.max(0, detailX + this.touch.offsetX), this.Width)
      this._offset(offset)
      this.$emit('changeCurrentTime', offset / this.Width)
    },
    touchend (e) {
      this.touchInit = false
    },
    _offset (offsetWidth) {
      this.$refs.progress.style.width = `${offsetWidth}px`
      this.$refs.progressBtn.style[transform] = `translate3d(${offsetWidth}px,0,0)`
    }
  },
  watch: {
    percent (news) {
      // 拖动时不要动
      if (news > 0 && !this.touchInit) {
        this.Width = this.$refs.progressBar.clientWidth - progressBtnWidth
        const offsetWidth = news * this.Width
        this._offset(offsetWidth)
      }
    }
  }
}
</script>
<style scoped lang='stylus'  rel='stylesheet/stylus'>
@import '~common/stylus/variable'
.inner
  position relative
  width 100%
  height 4px
  background rgba(0, 0, 0, 0.3)
  border-radius 4px
  .progess
    position absolute
    left 0
    top 0
    height 4px
    width 0
    z-index 1
    background $color-theme
    border-radius 4px
  .progress-btn
    position absolute
    left -3px
    top -6px
    width 16px
    height 16px
    background $color-theme
    border 3px solid #fff
    box-sizing border-box
    z-index 2
    border-radius 50%
</style>